#!/usr/bin/env node

const fs = require('node:fs')
const os = require('node:os')
const process = require('node:process')
const path = require('node:path')
const cp = require('node:child_process')
const fse = require('fs-extra')

const cwd = process.cwd()
const es = path.join(cwd, 'es')
const lib = path.join(cwd, 'lib')
const src = path.join(cwd, 'src')
const dist = path.join(cwd, 'dist')
const index = path.join(src, 'index.less')

function compile(source, target) {
  let cmd = '../../node_modules/.bin/lessc'
  if (os.type() === 'Windows_NT') {
    cmd = path.join(cwd, `${cmd}.cmd`)
  }
  cp.execFileSync(cmd, [source, target], { shell: true })
}

function toCSSPath(source) {
  const dir = path.dirname(source)
  const file = `${path.basename(source, '.less')}.css`
  return path.join(dir, file)
}

// Copy less files
function processLessInDir(dir) {
  const stat = fs.statSync(dir)
  if (stat) {
    if (stat.isDirectory()) {
      fs.readdir(dir, (err, files) => {
        files.forEach((file) => {
          processLessInDir(path.join(dir, file))
        })
      })
    } else {
      const ext = path.extname(dir)
      if (ext === '.less' || ext === '.css') {
        fse.copySync(dir, path.join(es, path.relative(src, dir)))
        fse.copySync(dir, path.join(lib, path.relative(src, dir)))
      }

      if (ext === '.less') {
        let source = path.join(es, path.relative(src, dir))
        let target = toCSSPath(source)
        compile(dir, target)

        source = path.join(lib, path.relative(src, dir))
        target = toCSSPath(source)
        compile(dir, target)
      }
    }
  }
}

function makeStyleModule() {
  const dir = path.join(src, 'style')
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir)
  }
  const source = path.join(dist, 'index.css')
  const target = path.join(dir, 'raw.ts')
  const content = fs.readFileSync(source, { encoding: 'utf8' })
  const prev = fs.existsSync(target)
    ? fs.readFileSync(target, { encoding: 'utf8' })
    : null
  const curr = `/* eslint-disable */

/**
 * Auto generated file, do not modify it!
 */

export const content = \`${content}\`
`

  if (prev !== curr) {
    fs.writeFileSync(target, curr)
  }
}

if (fs.existsSync(index)) {
  compile(index, path.join(es, 'index.css'))
  compile(index, path.join(lib, 'index.css'))
  compile(index, path.join(dist, 'index.css'))

  processLessInDir(src)
  makeStyleModule()
} else {
  // console.log(`style not found: ${index}`)
}
